<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="村名字" prop="villageName">
        <el-input
          v-model="queryParams.villageName"
          placeholder="请输入村名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网点名字">
        <el-input
          v-model="queryParams['bankBranchInstitutions.branchName']"
          placeholder="请输入网点名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户经理">
        <el-input
          v-model="queryParams['manager.nickName']"
          placeholder="请输入客户经理名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评议监督员">
        <el-input
          v-model="queryParams['supervisor.nickName']"
          placeholder="请输入评议监督员名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评议进度" prop="schedule">
        <el-select v-model="queryParams.schedule" placeholder="请选择评议进度" clearable>
          <el-option
            v-for="dict in dict.type.bank_schedule"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bank:village:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bank:village:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bank:village:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bank:village:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleOpenBlueListReview"
        >开启蓝名单复议</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleOpenBlueListReview1"
        >开启白名单复议</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="villageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="村编号" align="center" prop="villageId" />
      <el-table-column label="村名字" align="center" prop="villageName" />
      <el-table-column label="村介绍" align="center" prop="villageIntroduce" />
      <el-table-column label="评议轮数" align="center" prop="roundNumber">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bank_round_number" :value="scope.row.roundNumber"/>
        </template>
      </el-table-column>
      <el-table-column label="网点名字" align="center" prop="bankBranchInstitutions.branchName" />
      <el-table-column label="客户经理" align="center" prop="manager.nickName" />
      <el-table-column label="评议监督员" align="center" prop="supervisor.nickName" />
      <el-table-column label="评议进度" align="center" prop="schedule">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bank_schedule" :value="scope.row.schedule"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bank:village:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bank:village:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :visible.sync="dialogVisible">
      <p>温馨提示：开启蓝名单复议会将所有蓝名单户籍重新恢复为初始白名单，请再次确认是否需要开启蓝名单复议。</p>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          :disabled="countdown > 0"
          @click="confirmReview">
          确定{{ countdown > 0 ? `(${countdown})` : '' }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible1">
      <p>温馨提示：开启白名单复议会重置所有复议记录（白名单复议预授信金额和白名单复议评议员编号）。请再次确认是否需要开启白名单复议</p>
      <template #footer>
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button
          :disabled="countdown > 0"
          @click="confirmReview1">
          确定{{ countdown > 0 ? `(${countdown})` : '' }}
        </el-button>
      </template>
    </el-dialog>
    <!-- 添加或修改行政村管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="村名字" prop="villageName">
          <el-input v-model="form.villageName" placeholder="请输入村名字" />
        </el-form-item>
        <el-form-item label="村介绍" prop="villageIntroduce">
          <el-input v-model="form.villageIntroduce" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="评议轮数" prop="roundNumber">
          <el-select v-model="form.roundNumber" placeholder="请选择评议轮数">
            <el-option
              v-for="dict in dict.type.bank_round_number"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="网点名字" prop="branchId">
          <el-select v-model="form.branchId" placeholder="请选择网点名字">
            <el-option
              v-for="item in branchList"
              :key="item.branchId"
              :label="item.branchName"
              :value="item.branchId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户经理" prop="accountManagerId">
          <el-select v-model="form.accountManagerId" placeholder="请选择客户经理">
            <el-option
              v-for="item in managerList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评议监督员" prop="superVisorId">
          <el-select v-model="form.superVisorId" placeholder="请选择评议监督员">
            <el-option
              v-for="item in supervisorList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评议进度" prop="schedule">
          <el-select v-model="form.schedule" placeholder="请选择评议进度" disabled>
            <el-option
              v-for="dict in dict.type.bank_schedule"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVillage, getVillage, delVillage, addVillage, updateVillage } from "@/api/bank/village";
import {listBranch} from "@/api/bank/branch";
import {listUser} from "@/api/system/user";
import {listDomicile,updateDomicile} from "@/api/bank/domicile";
import {getAuthRole} from "@/api/system/user";
import{listSenator} from "@/api/bank/senator";
import{listVillagers} from "@/api/bank/villagers";

export default {
  name: "Village",
  dicts: ['bank_schedule', 'bank_round_number'],
  data() {
    return {
      dialogVisible: false,
      dialogVisible1: false,
      countdown: 10, // 初始倒计时10秒
      intervalId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行政村管理表格数据
      villageList: [],
      // 网点机构数据
      branchList:[],
      // 客户经理数据
      managerList:[],
      // 评议监督员数据
      supervisorList:[],
      // 户籍表信息
      domicileList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        villageName: null,
        'bankBranchInstitutions.branchName':null,
        'manager.nickName':null,
        'supervisor.nickName':null,
        branch: null,
        schedule: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        villageName: [
          { required: true, message: "村名字不能为空", trigger: "blur" }
        ],
        villageIntroduce: [
          { required: true, message: "村介绍不能为空", trigger: "blur" }
        ],
        roundNumber: [
          { required: true, message: "评议轮数不能为空", trigger: "change" }
        ],
        schedule: [
          { required: true, message: "评议进度不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getBranchList();
    this.getUserList();
    this.updateVillageProgress(); // 更新评议进度
    this.getList();

  },
  methods: {
    /** 查询行政村管理列表 */
    getList() {
      this.loading = true;
      listVillage(this.queryParams).then(response => {
        console.log('Village list received:', response.rows); // 打印接收到的行政村列表数据
        this.villageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    async getAllDomiciles() {
      const response = await listDomicile({pageSize:100000000});
      this.domicileList = response.rows; // 假设返回的数据在data字段中
    },

    async updateVillageProgress() {
      await this.getAllDomiciles(); // 获取所有户籍信息
      // 遍历每个行政村，更新评议进度
      for (const village of this.villageList) {
        // 筛选出属于当前村的户籍信息
        const domiciles = this.domicileList.filter(d => d.villageId === village.villageId);
        if (domiciles.length === 0) {
          continue; // 如果没有户籍信息，则跳过当前村的处理
        }

        let schedule = '0'; // 默认状态
        if (domiciles.every(d => d.domicileLabel === "2")) {
          schedule = '2';
        } else {
          const notCompleted = domiciles.filter(d => d.domicileLabel !== "2");
          if (notCompleted.every(d => d.domicileLabel == "1")) {
            schedule = '2';
          } else if (notCompleted.some(d => d.domicileVillagerId != null)) {
            schedule = '1';
          }
        }
        // 调用后端接口更新评议进度

        await updateVillage({villageId:village.villageId,schedule:schedule});
      }
      console.log("xxxxxx");
      this.getList(); // 这里调用getList方法来刷新列表
    },

    /** 查询网点机构列表 */
    getBranchList() {
      listBranch({pageSize:1000000}).then(response => {
        this.branchList = response.rows;

      });
    },
    /** 查询用户列表 */
    getUserList() {
      listUser({pageSize:100000}).then(async response => {
        const users = response.rows;
        const supervisorPromises = users.map(user => getAuthRole(user.userId));
        const roleResponses = await Promise.all(supervisorPromises);

        // 清空列表以防止重复
        this.supervisorList = [];
        this.managerList = [];

        roleResponses.forEach((roleResponse, index) => {
          const roles = roleResponse.user.roles; // 假设这是获取到的角色数组
          const user = users[index]; // 与角色响应相对应的用户
          // 检查用户角色并分类
          roles.forEach(role => {
            if (role.roleId == "8") {
              this.supervisorList.push(user);
            } else if (role.roleId == "9") {
              this.managerList.push(user);
            }
          });
        });
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        villageId: null,
        branchId: null,
        villageName: null,
        villageIntroduce: null,
        roundNumber: null,
        branch: null,
        accountManagerId: null,
        superVisorId: null,
        schedule: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.villageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.schedule='0';
      this.form.roundNumber='0'
      this.open = true;
      this.title = "添加行政村管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const villageId = row.villageId || this.ids
      getVillage(villageId).then(response => {
        this.form = {
          ...response.data,
          accountManagerId: response.data.accountManagerId || null,
          superVisorId: response.data.superVisorId || null
        };
        this.open = true;
        this.title = "修改行政村管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.villageId != null) {
            updateVillage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {

            addVillage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const villageIds = row.villageId ? [row.villageId] : this.ids; // 确保villageIds始终是数组形式
      const checkPromises = [
        listDomicile({ pageSize: 100000000 }),
        listSenator({ pageSize: 1000000 }),
        listVillagers({ pageSize: 100000000 })
      ];

      // 执行所有查询
      Promise.all(checkPromises).then(responses => {
        const [domicileResponse, senatorResponse, villagersResponse] = responses;
        const domiciles = domicileResponse.rows || [];
        const senators = senatorResponse.rows || [];
        const villagers = villagersResponse.rows || [];

        const undeletableVillageIds = villageIds.filter(villageId =>
          domiciles.some(d => d.villageId === villageId) ||
          senators.some(s => s.villageId === villageId) ||
          villagers.some(v => v.villageId === villageId)
        );

        const deletableVillageIds = villageIds.filter(villageId => !undeletableVillageIds.includes(villageId));

        // 显示错误提示信息
        if (undeletableVillageIds.length > 0) {
          if (undeletableVillageIds.length === villageIds.length) {
            // 如果所有选中的行政村都不可删除，只显示一条错误信息
            this.$modal.msgError("选中的行政村均存在关联的评议员信息，村民信息或户籍信息，无法删除");
          } else {
            // 如果部分行政村不可删除，显示具体的ID
            this.$modal.msgError(`行政村管理编号为"${undeletableVillageIds.join(', ')}"存在关联的评议员信息，村民信息或户籍信息，不允许删除`);
          }
        }

        // 如果有可删除的行政村
        if (deletableVillageIds.length > 0) {
          this.$modal.confirm(`是否确认删除行政村管理编号为"${deletableVillageIds.join(', ')}"的数据项？`).then(() => {
            // 直接传递数组到接口
            return delVillage(deletableVillageIds);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        }
      }).catch(error => {
        console.error("检查行政村信息时发生错误: ", error);
        this.$modal.msgError("检查行政村信息时发生错误，请稍后再试");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bank/village/export', {
        ...this.queryParams
      }, `village_${new Date().getTime()}.xlsx`)
    },
    handleOpenBlueListReview() {
      if (this.intervalId) {
        clearInterval(this.intervalId); // 清除现有的计时器
      }
      this.countdown = 10; // 重置倒计时为10秒
      this.intervalId = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown -= 1;
        } else {
          clearInterval(this.intervalId);
        }
      }, 1000);
      this.dialogVisible = true;
    },
    handleOpenBlueListReview1() {
      if (this.intervalId) {
        clearInterval(this.intervalId); // 清除现有的计时器
      }
      this.countdown = 10; // 重置倒计时为10秒
      this.intervalId = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown -= 1;
        } else {
          clearInterval(this.intervalId);
        }
      }, 1000);
      this.dialogVisible1 = true;
    },
    async confirmReview1() {
      try {
        const domicileResponse = await listDomicile({pageSize: 100000000});
        const domiciles = domicileResponse.rows;
        // 遍历户籍信息
        for (let domicile of domiciles) {
          if (domicile.domicileLabel === '1') {
            await updateDomicile({
              domicileId: domicile.domicileId,
              whiteMoney: 0,
              whiteSenatorId: 0
            });

          }
        }
        this.$modal.msgSuccess("开启白名单复议成功");
        this.dialogVisible1 = false; // 关闭对话框
      } catch (error) {
        console.error("执行白名单复议逻辑时出错：", error);
        this.$modal.msgError("开启白名单复议失败，请稍后再试");
        this.dialogVisible1 = false; // 关闭对话框
      }
    },
    async confirmReview() {
      try {
        const domicileResponse = await listDomicile({pageSize: 100000000});
        const domiciles = domicileResponse.rows; // 假设接口返回的数据在data字段中

        const villagersResponse = await listVillagers({pageSize: 100000000});
        const villagers = villagersResponse.rows; // 同上

        // 遍历户籍信息
        for (let domicile of domiciles) {
          if (domicile.domicileLabel === '2') {

            const relatedVillagers = villagers.filter(villager => villager.villagerDomicileNumber === domicile.domicileNumber);

            // 检查是否存在年龄在22到59之间的村民
            if (relatedVillagers.some(villager => villager.villagerAge >= 22 && villager.villagerAge <= 59)) {
              // 更新户籍标签为“0”
              await updateDomicile({
                domicileId: domicile.domicileId,
                domicileLabel: '0'
              });

            }
          }
        }
        this.getList();
        this.$modal.msgSuccess("开启蓝名单复议成功");
        this.dialogVisible = false; // 关闭对话框
      } catch (error) {
        console.error("执行蓝名单复议逻辑时出错：", error);
        this.$modal.msgError("开启蓝名单复议失败，请稍后再试");
        this.dialogVisible = false; // 关闭对话框
      }
    }
  }
};
</script>
